package com.sskj.one;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.textservice.SpellCheckerInfo;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.sskj.common.adapter.MyFragmentPagerAdapter;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.GSonUtil;
import com.sskj.common.util.PermissionTipUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.widget.ViewPagerSlide;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.DownMusicBean;
import com.sskj.lib.bean.TabItem;
import com.sskj.lib.util.APKVersionCodeUtils;
import com.sskj.lib.util.TipUtil;
import com.sskj.one.banker.BankerFragment;
import com.sskj.one.banker.DividendActivity;
import com.sskj.one.bean.MusicBean;
import com.sskj.one.bean.TanChuangBean;
import com.sskj.one.bean.UpdataBean;
import com.sskj.one.bean.bus.TabBean;
import com.sskj.one.jpush.PushTypeBean;
import com.sskj.one.login.AppUpDateFragment;
import com.sskj.one.mine.MineFragment;
import com.sskj.one.proxy.ProxyFragment;
import com.sskj.one.proxy.TeamLevelActivity;
import com.sskj.one.service.MarketWebSocket;
import com.sskj.one.transaction.TransactionFragment;
import com.sskj.one.util.MusicControl;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.util.ArrayList;
import java.util.Objects;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

@Route(path = RConfig.APP_MAIN)
public class MainActivity extends BaseActivity<MainPresneter> {

    @BindView(R.id.viewPager)
    ViewPagerSlide viewPager;
    @BindView(R.id.tab_layout)
    CommonTabLayout tabLayout;

    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    ArrayList<Fragment> fragments = new ArrayList<>();
    MarketWebSocket marketWebSocket;

    private MediaPlayer mediaPlayer;
    private String musicPath;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        RxBus.getDefault().register(this);

        musicPath = SPUtil.get(SPConfig.MUSIC_PATH, "");

        tabEntities.add(new TabItem("交易", R.mipmap.icon_transcation, R.mipmap.icon_transcation_t));
        tabEntities.add(new TabItem("代理", R.mipmap.icon_proxy, R.mipmap.icon_proxy_t));
        tabEntities.add(new TabItem("股东", R.mipmap.icon_banker, R.mipmap.icon_banker_t));
        tabEntities.add(new TabItem("我的", R.mipmap.icon_mine, R.mipmap.icon_mine_t));
        fragments.add(TransactionFragment.newInstance());
        fragments.add(ProxyFragment.newInstance());
        fragments.add(BankerFragment.newInstance());
        fragments.add(MineFragment.newInstance());
        tabLayout.setTabData(tabEntities);
        tabLayout.setCurrentTab(0);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position, true);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        viewPager.setSlide(false);
        viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.setCurrentTab(0);

        mediaPlayer = new MediaPlayer();
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.checkVersion(APKVersionCodeUtils.getVerName(App.INSTANCE));
        mPresenter.getMusic();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String type = bundle.getString(JPushInterface.EXTRA_EXTRA);
            //type 1 团队分级 2 历史分红
            if (!isEmpty(type)) {
                PushTypeBean pushTypeBean = GSonUtil.GsonToBean(type, PushTypeBean.class);
                if ("1".equals(pushTypeBean.getType())) {
                    TeamLevelActivity.start(MainActivity.this);
                } else if ("2".equals(pushTypeBean.getType())) {
                    DividendActivity.start(MainActivity.this, Constans.DIVIDEND_HISTORY);
                }
            }
        }
    }

    @Override
    public MainPresneter getPresenter() {
        return new MainPresneter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startWebSocket();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeTab(TabBean tabBean) {
        if (tabLayout != null) {
            tabLayout.setCurrentTab(tabBean.getTabPos());
            viewPager.setCurrentItem(tabBean.getTabPos());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void controlMusic(String type) {
        if (isEmpty(musicPath)) {
            mPresenter.getMusic();
            return;
        }
        if ("1".equals(musicPath)) {
            ToastUtils.show("音乐准备中，请稍等片刻");
            return;
        }
        if (Objects.equals(SPUtil.get(SPConfig.MUSIC_ONE, ""), "1")) {
            mediaPlayer = new MediaPlayer();
            MusicControl.play(mediaPlayer, musicPath);
        } else {
            MusicControl.stop(mediaPlayer);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeMarket();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        mediaPlayer = null;
    }

    public void startWebSocket() {
        closeMarket();
        marketWebSocket = new MarketWebSocket(BaseHttpConfig.WS_BASE_URL, "", "get_price");
        marketWebSocket.setLogEnable(true);
        marketWebSocket.setListener(message -> {
            CoinBean coinBean = GSonUtil.GsonToBean(message, CoinBean.class);
            if (coinBean != null) {
                RxBus.getDefault().post(coinBean);
            }
        });
    }

    private void closeMarket() {
        if (marketWebSocket != null) {
            marketWebSocket.closeWebSocket();
            marketWebSocket = null;
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public void getMusicOK(MusicBean data) {
        if (data == null) {
            return;
        }
        if (SPUtil.get(SPConfig.MUSIC_URL, "").equals(data.getAddr_muisc())) {
            if (!isEmpty(SPUtil.get(SPConfig.MUSIC_PATH, ""))) {
                musicPath = SPUtil.get(SPConfig.MUSIC_PATH, "");
                if (Objects.equals(SPUtil.get(SPConfig.MUSIC_ONE, ""), "1")) {
                    MusicControl.play(mediaPlayer, musicPath);
                }
                return;
            }
        } else {
            SPUtil.put(SPConfig.MUSIC_URL, data.getAddr_muisc());
        }
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(isGrant -> {
                    if (isGrant) {
                        OkGo.<File>get(data.getAddr_muisc()).execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                musicPath = response.body().getPath();
                                SPUtil.put(SPConfig.MUSIC_PATH, response.body().getPath());
                                if (SPUtil.get(SPConfig.MUSIC_ONE, "").equals("1")) {
                                    MusicControl.play(mediaPlayer, musicPath);
                                }
                            }

                            @Override
                            public void onStart(Request<File, ? extends Request> request) {
                                super.onStart(request);
                                musicPath = "1";
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                            }

                            @Override
                            public void onError(Response<File> response) {
                                super.onError(response);
                                ToastUtils.show("音乐文件下载失败");
                            }
                        });
                    } else {
                        PermissionTipUtil.tip(this, "存储");
                    }
                });
    }


    public void checkVersionOK(UpdataBean data) {
        if (data == null) {
            return;
        }

        String verName = APKVersionCodeUtils.getVerName(this);
        data.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(data.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            data.setViewStyle(BaseVersion.DEFAULT_STYLE);
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, data);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
        }

    }

    public void getGongGaoOK(TanChuangBean data) {
        if (data == null) {
            return;
        }

        TipUtil.showGonggao(MainActivity.this, data.getTitle(), data.getContent());

    }
}
